const navigator = weex.requireModule('navigator')
const modal = weex.requireModule('modal')

const router = {}

router.getBaseUrl = function () {
  let bundleUrl = weex.config.bundleUrl

  let nativeBase

  let isAndroidAssets = bundleUrl.indexOf('file://assets/') >= 0

  let isiOSAssets = bundleUrl.indexOf('file:///') >= 0 && bundleUrl.indexOf('WeexDemo.app') > 0

  if (isAndroidAssets) {
      nativeBase = 'http://192.168.123.109:8081/dist/'
  }
  else if (isiOSAssets) {
      nativeBase = bundleUrl.substring(0, bundleUrl.lastIndexOf('/') + 1)
  }
  else {
      var host
      var matches = /\/\/([^\/]+?)\//.exec(bundleUrl)
      if (matches && matches.length >= 2) {
          host = matches[1]
      }

      // if (typeof window === 'object') {
      //     nativeBase = isnav ? 'http://' + host + '/index.html?page=./dist/' : '/dist/'
      // } else {
      nativeBase = 'http://' + host + '/dist/'
      // }
  }

  return nativeBase
}

router.push = (params, callback) => {
  if(typeof params !== 'object') return
  if(!params.hasOwnProperty('url') && !params.hasOwnProperty('animated')) return
  if(/^\w+$[\/]{0,1}/.test(params.url) && params.url.search(/[\.]/g) == -1 && typeof params.animated == 'string' && typeof callback == 'function') {
    params.url = router.getBaseUrl() + params.url + '.js'
    navigator.push(params, callback)
  }
  else {
    modal.toast({message: `找不到相关${params.url}路径`})
  }
}

router.pop = (params, callback) => {
  if(!params.hasOwnProperty('animated')) return
  if(typeof params.animated == 'string' && typeof callback == 'function') {
    navigator.pop(params, callback)
  }
}

module.exports = router